from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from app.models import Sample
from app import db
from datetime import datetime

bp = Blueprint('data', __name__, url_prefix='/data')

@bp.route('/')
@login_required
def index():
    samples = Sample.query.filter_by(user_id=current_user.id).order_by(Sample.created_at.desc()).all()
    return render_template('data/index.html', samples=samples)

@bp.route('/add', methods=['GET', 'POST'])
@login_required
def add():
    if request.method == 'POST':
        try:
            sample = Sample(
                sample_id=request.form['sample_id'],
                variety_name=request.form['variety_name'],
                collection_date=datetime.strptime(request.form['collection_date'], '%Y-%m-%d'),
                location=request.form['location'],
                hardness=float(request.form['hardness']) if request.form['hardness'] else None,
                protein_content=float(request.form['protein_content']) if request.form['protein_content'] else None,
                moisture_content=float(request.form['moisture_content']) if request.form['moisture_content'] else None,
                notes=request.form['notes'],
                user_id=current_user.id
            )
            
            db.session.add(sample)
            db.session.commit()
            flash('样品数据添加成功', 'success')
            return redirect(url_for('data.index'))
            
        except ValueError as e:
            flash('数据格式错误，请检查输入', 'danger')
        except Exception as e:
            db.session.rollback()
            flash(f'添加失败：{str(e)}', 'danger')
    
    return render_template('data/add.html')

@bp.route('/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit(id):
    sample = Sample.query.get_or_404(id)
    
    # 确保只能编辑自己的数据
    if sample.user_id != current_user.id:
        flash('无权限编辑此数据', 'danger')
        return redirect(url_for('data.index'))
    
    if request.method == 'POST':
        try:
            sample.sample_id = request.form['sample_id']
            sample.variety_name = request.form['variety_name']
            sample.collection_date = datetime.strptime(request.form['collection_date'], '%Y-%m-%d')
            sample.location = request.form['location']
            sample.hardness = float(request.form['hardness']) if request.form['hardness'] else None
            sample.protein_content = float(request.form['protein_content']) if request.form['protein_content'] else None
            sample.moisture_content = float(request.form['moisture_content']) if request.form['moisture_content'] else None
            sample.notes = request.form['notes']
            
            db.session.commit()
            flash('样品数据更新成功', 'success')
            return redirect(url_for('data.index'))
            
        except ValueError as e:
            flash('数据格式错误，请检查输入', 'danger')
        except Exception as e:
            db.session.rollback()
            flash(f'更新失败：{str(e)}', 'danger')
    
    return render_template('data/edit.html', sample=sample)

@bp.route('/delete/<int:id>', methods=['POST'])
@login_required
def delete(id):
    sample = Sample.query.get_or_404(id)
    
    # 确保只能删除自己的数据
    if sample.user_id != current_user.id:
        flash('无权限删除此数据', 'danger')
        return redirect(url_for('data.index'))
    
    try:
        db.session.delete(sample)
        db.session.commit()
        flash('样品数据删除成功', 'success')
    except Exception as e:
        db.session.rollback()
        flash(f'删除失败：{str(e)}', 'danger')
    
    return redirect(url_for('data.index'))
